/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#pragma once
#include <list>
#include <memory>
#include <string>

#include "framework/event.h"
#include "framework/worker.h"

namespace air {
namespace link {

class Msg;
class EventConnManager;
class EventConn final : public Event {
  friend class App;
  friend class EventConnManager;

 public:
  EventConn();
  virtual ~EventConn();

  int GetFd() override;
  EventType GetEventType() override;
  unsigned int ListenEpollEventType() override;
  void RetEpollEventType(uint32_t ev) override;

  std::shared_ptr<Msg> SendRequest(const std::string& dst,
                                   std::shared_ptr<Msg> req);

 private:
  std::string GetEvConnName();
  void SetEvConnName(const std::string& name);

  int SendCmdToWorker(const WorkerCmd& cmd);
  int RecvCmdFromWorker(WorkerCmd* cmd);

  int RecvCmdFromMain(WorkerCmd* cmd, int timeout_ms = -1);
  int SendCmdToMain(const WorkerCmd& cmd);

  bool CreateSockPair();
  void CloseSockPair();
  int sockpair_[2];

  /// 接收消息队列
  std::list<std::shared_ptr<Msg>> recv_;
  /// 发送消息队列
  std::list<std::shared_ptr<Msg>> send_;

  std::string ev_conn_name_{""};
};

}  // namespace link
}  // namespace air
